package com.qiantu.phone.widget;

import android.content.Context;
import android.content.res.Resources;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bigkoo.pickerview.adapter.ArrayWheelAdapter;
import com.contrarywind.view.WheelView;
import com.qiantu.api.entity.DeviceBindingData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppApplication;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class OperateBindView extends BasePopupView {
    public String coreId;
    public int bindType = 0;//0为开光绑定，1为面板绑定
    private CircleCountDownTimeView countDownView;
    private Map<WheelData, List<WheelData>> wheelMaps; //开关模式选择Map
    private WheelView switchWheelView, switchOperateWheelView;
    private TextView tvActionOperation;
    private TextView tvOperation;
    private TextView tvHint1;
    private TextView tvHint2;
    private TextView tvHint3;

    private Callback callback;
    private boolean noNextStep = false;
//    是否显示二级菜单
    private boolean showChildView = true;

    public OperateBindView(@NonNull Context context) {
        super(context);
    }

    public OperateBindView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected View loadLayout(Context context) {
        return View.inflate(context, R.layout.view_operate_bind, null);
    }

    @Override
    protected void initView(Context context) {
        tvActionOperation = findViewById(R.id.tv_action_operation);
        tvOperation = findViewById(R.id.tv_operation_button);
        tvHint1 = findViewById(R.id.tv_hint_1);
        tvHint2 = findViewById(R.id.tv_hint_2);
        tvHint3 = findViewById(R.id.tv_hint_3);
        initCountDownView();
        initWheelView();
        findViewById(R.id.button_ok).setOnClickListener(v -> {
            if(!noNextStep){
                setVisibilityBind(R.id.layout_switch_operate, GONE);
                setVisibilityBind(R.id.layout_countdown, VISIBLE);
            }
            bindSwitch();//绑定开关
        });
    }

    private void bindSwitch() {
        if (noWheelData){
            callback.requestInit("", "", "", 0, 0);
        }else {
            //开始执行初始化操作。需要请求init绑定开关然后去等待倒计时
            WheelData keyId = (WheelData) switchWheelView.getAdapter().getOriginItem(switchWheelView.getCurrentItem());
            String bindDataName = (String) keyId.value;
            String bindDataValueName = wheelMaps.get(keyId).get(switchOperateWheelView.getCurrentItem()).key;
            Object bindDataValue = wheelMaps.get(keyId).get(switchOperateWheelView.getCurrentItem()).value;
            int bindActionType = wheelMaps.get(keyId).get(switchOperateWheelView.getCurrentItem()).bindActionType;
            int actionType = wheelMaps.get(keyId).get(switchOperateWheelView.getCurrentItem()).actionType;
            if(bindDataName == null || !bindDataName.equals("color")){
                callback.requestInit(bindDataName, bindDataValueName, bindDataValue, bindActionType, actionType);
            }else {
                Map<String,Integer> map = wheelMaps.get(keyId).get(switchOperateWheelView.getCurrentItem()).otherValue;
                callback.requestInit(bindDataName, bindDataValueName, map, bindActionType, actionType);
            }
        }
        if(bindType == 1){
            tvOperation.setText(R.string.panel_bind);
            setTextViewBind(R.id.operate_switch_hint, R.string.panel_bining);
            tvHint1.setVisibility(GONE);
            tvHint2.setVisibility(GONE);
            tvHint3.setVisibility(GONE);
        }else{
            tvOperation.setText(R.string.operate_switch);
            setTextViewBind(R.id.operate_switch_hint, R.string.operate_switch_ready);
            tvHint1.setVisibility(VISIBLE);
            tvHint2.setVisibility(VISIBLE);
            tvHint3.setVisibility(VISIBLE);
        }
    }

    private void initWheelView() {
        switchWheelView = findViewById(R.id.switch_wheel_view);
        switchOperateWheelView = findViewById(R.id.switch_operate_wheel_view);
        setStyle(switchWheelView);
        setStyle(switchOperateWheelView);
        switchWheelView.setOnItemSelectedListener(index -> {
            WheelData keyId = (WheelData) switchWheelView.getAdapter().getOriginItem(index);
            List<WheelData> valueData = wheelMaps.get(keyId);
            switchOperateWheelView.setAdapter(new ArrayWheelAdapter<WheelData>(valueData) {
                @Override
                public Object getItem(int index) {
                    WheelData wheelData = (WheelData) super.getOriginItem(index);
                    return wheelData.getKey();//key显示在界面 value传到接口
                }
            });
        });
    }

    private void initCountDownView() {
        countDownView = findViewById(R.id.operate_switch_countdown);
        countDownView.setListener(new CircleCountDownTimeView.CountDownListener() {
            @Override
            public void onTimeout() {
                removeCallbacks(pollingRunnable);
                if(bindType == 1){
                    setTextViewBind(R.id.operate_switch_hint, R.string.panel_bind_fail);
                }else {
                    setTextViewBind(R.id.operate_switch_hint, R.string.operate_switch_failed);
                }
            }

            @Override
            public void onRetry() {
                if(bindType == 1){
                    setTextViewBind(R.id.operate_switch_hint, R.string.panel_bining);
                }else {
                    setTextViewBind(R.id.operate_switch_hint, R.string.operate_switch_ready);
                }
                bindSwitch();
            }
        });
        countDownView.setMode(CircleCountDownTimeView.CountDownMode.RUNNING, null);
        countDownView.setCountdownTime(10);
    }

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    private boolean noWheelData;
    public void setInfoBean(List<DeviceBindingData> bindingData) {
        if (bindingData == null){
            noWheelData = true;
            return;
        }else {
            noWheelData = false;
        }
        wheelMaps = new LinkedHashMap<>();
        for (DeviceBindingData data : bindingData) {
            int keyId = getResources().getIdentifier(data.getName(), "string", getContext().getPackageName());
            if (data.getData() != null && data.getData().size() > 0) {
                List<WheelData> switchOperateList = new ArrayList<>();
                for (DeviceBindingData.Data d : data.getData()) {
                    String title = "";
                    try {
                        int valueId = getResources().getIdentifier(d.getName(), "string", getContext().getPackageName());
                        title = getResources().getString(valueId);
                    }catch (Resources.NotFoundException e){
                        title = d.getName();
                    }
                    switchOperateList.add(new WheelData(title, d.getValue(), d.getOtherValue(), d.getBindActionType(), data.getActionType()));
                }
                if(keyId == 0){
                    wheelMaps.put(new WheelData(data.getName(), data.getKey()), switchOperateList);
                }else{
                    wheelMaps.put(new WheelData(getResources().getString(keyId), data.getKey()), switchOperateList);
                }

            } else {
                List<WheelData> modeOperateList = new ArrayList<>();
                for (int i = data.getMin(); i < data.getMax(); i += data.getStep()) {
                    modeOperateList.add(new WheelData(i + "", i, i, data.getActionType()));
                }
                modeOperateList.add(new WheelData(data.getMax() + "", data.getMax(), data.getMax(), data.getActionType()));
                wheelMaps.put(new WheelData(getResources().getString(keyId), data.getKey()), modeOperateList);
            }
        }
        switchWheelView.setAdapter(new ArrayWheelAdapter<WheelData>(new ArrayList<>(wheelMaps.keySet())) {
            @Override
            public Object getItem(int index) {
                WheelData wheelData = (WheelData) super.getItem(index);
                return wheelData.getKey();//界面上显示key 传接口显示value
            }
        });
        switchOperateWheelView.setAdapter(new ArrayWheelAdapter<WheelData>(new ArrayList<>(wheelMaps.values()).get(0)) {
            @Override
            public Object getItem(int index) {
                WheelData wheelData = (WheelData) super.getOriginItem(index);
                return wheelData.getKey();//key显示在界面 value传到接口
            }
        });
    }

    public void setActionStr(String actionStr){
        tvActionOperation.setText(actionStr);
    }

    private void setStyle(WheelView wheelView) {
        wheelView.setGravity(Gravity.CENTER);
        wheelView.setCyclic(false);
        wheelView.setAlphaGradient(true);
//        wv_first.setLabelOffset(5);
        wheelView.setItemsVisibleCount(5);
        wheelView.setDividerColor(0x00000000);
        wheelView.setTextColorCenter(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
        wheelView.setTextSize(getResources().getDimensionPixelSize(R.dimen.dp_18));
    }

    public void startWait10SecondAnimator(String coreId) {
        this.coreId = coreId;
        if(bindType == 1){
            setTextViewBind(R.id.operate_switch_hint, R.string.panel_bining);
        }else {
            setTextViewBind(R.id.operate_switch_hint, R.string.operate_switch_ready);
        }
        countDownView.setMode(CircleCountDownTimeView.CountDownMode.RUNNING, null);
        countDownView.startAnimator(getResources().getText(R.string.rebind).toString());
        postDelayed(pollingRunnable, 2000);//2秒后开始轮询
    }

    public void startWaitWithoutAnimator(String coreId) {
        this.coreId = coreId;
        postDelayed(pollingRunnable, 2000);//2秒后开始轮询

    }

    public void endWait() {
        removeCallbacks(pollingRunnable);

    }

    private final Runnable pollingRunnable = new Runnable() {
        @Override
        public void run() {
            callback.requestInitQuery(coreId);
            postDelayed(pollingRunnable, 2000);//2秒后开始轮询
        }
    };

    @Override
    public void setVisibility(int visibility) {
        super.setVisibility(visibility);
        if (visibility == VISIBLE) {
            if (noWheelData){
                findViewById(R.id.button_ok).performClick();
            }else {
                //初始化UI 让开关显示在前面 倒计时先隐藏
                setVisibilityBind(R.id.layout_switch_operate, VISIBLE);
                setVisibilityBind(R.id.layout_countdown, GONE);
            }
        } else if (visibility == GONE && countDownView.getMode() == CircleCountDownTimeView.CountDownMode.RUNNING) {
            //正在关闭当前弹窗 但是动画正在进行 需要手动关闭
            countDownView.stopAnimator(false, "00:00");
        }
    }

    public void setBindType(int bindType){
        this.bindType = bindType;
    }

    /**
     * 绑定失败
     */
    public void failedBind() {
        countDownView.stopAnimator(false, getResources().getString(R.string.rebind));
    }

    /**
     * 存在绑定
     */
    public void hasBind() {
        countDownView.stopAnimator(true, getResources().getString(R.string.has_bind));
    }

    /**
     * 绑定成功
     */
    public void bindComplete() {
        removeCallbacks(pollingRunnable);
        countDownView.stopAnimator(true, getResources().getString(R.string.binding_success));
        show(3, new DelayTimeCallBack() {
            @Override
            public void callback(int time) {
                String s = String.format(getContext().getString(R.string.operate_switch_success_time_close), ""+time);
                setTextViewBind(R.id.operate_switch_hint, s);
            }
        });
    }

    public void bindComplete(DelayTimeCallBack listener) {
        countDownView.stopAnimator(true, getResources().getString(R.string.binding_success));
        show(3, new DelayTimeCallBack() {
            @Override
            public void callback(int time) {
                String s = String.format(getContext().getString(R.string.operate_switch_success_time_close), ""+time);
                setTextViewBind(R.id.operate_switch_hint, s);
                if (time == 1){
                    listener.callback(time);
                }
            }
        });
    }

    /**
     * 覆盖成功
     */
    public void coverComplete() {
        removeCallbacks(pollingRunnable);
        countDownView.stopAnimator(true, getResources().getString(R.string.binding_cover_success));
        show(3, new DelayTimeCallBack() {
            @Override
            public void callback(int time) {
                String s = String.format(getContext().getString(R.string.operate_switch_success_time_close), ""+time);
                setTextViewBind(R.id.operate_switch_hint, s);
            }
        });
    }

//    public void continueWait() {
//        //只有动画还在执行才能继续等待
//        if (countDownView.getMode() == CircleCountDownTimeView.CountDownMode.RUNNING)
//            postDelayed(pollingRunnable, 2000);//2秒后开始轮询
//    }

    private static final class WheelData {
        private String key;
        private Object value;
        private Map<String,Integer> otherValue;
        private int bindActionType;
        private int actionType;

        public WheelData(String key, Object value, Map<String,Integer> otherValue, int bindActionType, int actionType) {
            this.key = key;
            this.value = value;
            this.otherValue = otherValue;
            this.bindActionType = bindActionType;
            this.actionType = actionType;
        }

        public WheelData(String key, Object value, int bindActionType, int actionType) {
            this.key = key;
            this.value = value;
            this.bindActionType = bindActionType;
            this.actionType = actionType;
        }

        public WheelData(String key, Object value) {
            this.key = key;
            this.value = value;
        }

        public int getBindActionType() {
            return bindActionType;
        }

        public void setBindActionType(int bindActionType) {
            this.bindActionType = bindActionType;
        }

        public int getActionType() {
            return actionType;
        }

        public void setActionType(int actionType) {
            this.actionType = actionType;
        }

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public Object getValue() {
            return value;
        }

        public void setValue(Object value) {
            this.value = value;
        }

        public Map<String, Integer> getOtherValue() {
            return otherValue;
        }

        public void setOtherValue(Map<String, Integer> otherValue) {
            this.otherValue = otherValue;
        }
    }

    public interface Callback {
        void requestInit(String statusKey, String statusValueName, Object statusValue, int bindActionType, int actionType);

        void requestInitQuery(String coreId);
    }

    private int dismissTime;
    private DelayTimeCallBack callBack;
    public void show(int time, DelayTimeCallBack callBack){
        if (getVisibility() != VISIBLE){
            setVisibility(VISIBLE);
        }
        dismissTime = time;
        this.callBack = callBack;
        hideTime();
    }

    public interface DelayTimeCallBack {
        void callback(int time);
    }

    private void hideTime(){
        if (getVisibility() != VISIBLE) return;
        if (dismissTime<=0){
            setVisibility(GONE);
        }else {
            callBack.callback(dismissTime--);
            postDelayed(new Runnable() {
                @Override
                public void run() {
                    hideTime();
                }
            }, 1000);
        }
    }

    public void setNoNextStep(Boolean noNextStep){
        this.noNextStep = noNextStep;
    }

    public void setShowChildView(boolean showChildView){
        this.showChildView = showChildView;
        if(showChildView){
            switchOperateWheelView.setVisibility(VISIBLE);
        }else{
            switchOperateWheelView.setVisibility(GONE);
        }
    }
}
